package tt.dz.scheduletask.tasks;

import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import tt.dz.scheduletask.ScheduledTask;
import tt.dz.service.imp.middleware.instruction.Ev3c2Instructions;
import tt.dz.service.imp.middleware.instruction.Ev3cInstructions;
import tt.dz.service.imp.middleware.instruction.Instruction;
import tt.dz.service.imp.middleware.instruction.InstructionType;
import tt.dz.service.imp.middleware.vo.ProtocolVersion;
import tt.dz.service.imp.middleware.vo.UnSendingMessage;
import tt.dz.tcp.socket.LongConnectionSendMsgImpl;
import tt.dz.tcp.socket.exception.CreateConnectionFailException;
import tt.dz.tcp.socket.exception.RetryFailException;
import tt.dz.tcp.socket.timeoff.MsgTimeOffHandlerFactory;
import tt.dz.util.RedisClient;

import java.util.*;

@Component
public class ChargerMessageReSender implements ScheduledTask
{
	private Log log = LogFactory.getLog(ChargerMessageReSender.class);

	private static final String resender_key_patten = "unsendmsg_*";

	@Value(value = "${communication.message.timeoff.sec}")
	private int TIME_OFF_SEC;

	@Value(value = "${minimum.message.sending.interval.sec}")
	private int MINIMUM_SENDING_INTERVAL;

	@Autowired
	LongConnectionSendMsgImpl client;

	//超时重发的时间由桩回复的速度进行改变，对spring-task.xml文件修改即可
	@Override
	public void execute()
	{
		Date now = new Date();
		Jedis jedis = null;
		try
		{
			jedis = RedisClient.getConnect();
			Set<String> keys = jedis.keys(resender_key_patten);
			for (String key : keys)
			{
				ArrayList<String> list_msgstring = new ArrayList<>();
				while (true)
				{
					String m = jedis.lpop(key);
					if (m == null)
						break;
					list_msgstring.add(m);
				}

				for (int i = 0; i < list_msgstring.size(); i++)
				{
					String msgstring = list_msgstring.get(i);
					UnSendingMessage msg = JSON.parseObject(msgstring, UnSendingMessage.class);
					if (isTimeOff(msg, now))
					{
						try
						{
							log.info("time-off for " + msg.getChargerId());
							MsgTimeOffHandlerFactory.getTimeOffHandler(msg).handleTimeOff();
						}
						catch (Exception ex)
						{
							log.error(ex.getMessage(), ex);
						}

						continue;
					}

					if(laterThanMinimumSendingInterval(msg, now))
					{
						try
						{
							log.info("re-send message to charger" + msg.getChargerId());
							client.resend(msg.getMessage(), msg.getChargerId());
						}
						catch (RetryFailException | CreateConnectionFailException e)
						{
							log.error(e.getMessage(), e);
						}
					}
					jedis.rpush(key, msgstring);
				}
			}

		}
		catch (Exception e)
		{
			log.error(e.getMessage(), e);
		}
		finally
		{
			if (jedis != null)
				jedis.close();
		}
	}

	private boolean isTimeOff(UnSendingMessage msg, Date now)
	{
		return (now.getTime() - msg.getCreateDt().getTime()) / 1000 > TIME_OFF_SEC;
	}

	private boolean laterThanMinimumSendingInterval(UnSendingMessage msg, Date now)
	{
		return (now.getTime() - msg.getCreateDt().getTime()) / 1000 > MINIMUM_SENDING_INTERVAL;
	}
}